package counter.com.myservice;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;


/**
 * 服务器
 *
 * @author OnlyMate
 * @ClassName: WebSocket
 * @Description: TODO
 * @Date 2018年8月16日 下午2:46:54
 */
@Component
@ServerEndpoint(value = "/websocket/{username}")
@Slf4j
public class WebSocket {

    private Session session;
    private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();

    /**
     * 建立连接
     *
     * @param session
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username) {
        this.session = session;
        webSockets.add(this);
        System.out.println("WEBSOCKET 新建链接" + username);
        log.info("【新建连接】" + username + "，连接总数:{}", webSockets.size());
    }

    /**
     * 断开连接
     */
    @OnClose
    public void onClose(@PathParam("username") String username) {
        webSockets.remove(this);
        System.out.println("WEBSOCKET 断开");
        log.info("【断开连接】，连接总数:{}", webSockets.size());
    }

    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("WEBSOCKET 发生错误");
        log.error("webSocket发生错误！session：{}", session);
        error.printStackTrace();
    }


    /**
     * 接收到信息
     *
     * @param message
     */
    @OnMessage
    public void onMessage(Session session, String message) {
//        System.out.println("WEBSOCKET 收到" + session.getId() + message);
        log.info("【收到】，客户端的信息:{}，连接总数:{}", message, webSockets.size());
        sendMessage("nihao");
    }

    /**
     * 发送消息
     * @param message
     */
    public static void sendMessage(String message) {
//        System.out.println("WEBSOCKET 发送" + message);
        log.info("【广播发送】，信息:{}，总连接数:{}", message, webSockets.size());
        for (WebSocket webSocket : webSockets) {
            try {
                webSocket.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                log.info("【广播发送】，信息异常:{}", e.fillInStackTrace());
            }
        }
    }
}